package com.umpay.privi.interceptor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.umpay.privi.common.ReqMessage;
import com.umpay.privi.common.ResMessage;
import com.umpay.privi.common.RetCode;
import com.umpay.privi.exception.BusinessException;
import com.umpay.privi.util.PropertiesUtil;
import com.umpay.privi.util.StringUtil;

/** 
 * desc:接入拦截器，打印简要日志
 * <p>创建人：Ding Zhe 创建日期：Apr 26, 2013 </p>
 * @version V1.0  
 */
public class AccessInterceptor {
	
	private static final Logger log_ = LoggerFactory.getLogger("mpspLogger");
	
	@AroundInvoke
	public Object profile(InvocationContext ctx) throws Exception{
		long beginTime = System.currentTimeMillis();
		
		ResMessage res = new ResMessage();
		Object[] paras = ctx.getParameters();
		
		if(paras.length!=1){
			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
			res.setRetCode(RetCode.REQPARAM_ERR);
			res.setRetMsg("请求参数个数错误");
			log_.info("错误返回:"+res);
			return res;
		}
		Object o = paras[0];
		if(o == null || !(o instanceof ReqMessage)){
			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
			res.setRetCode(RetCode.REQPARAM_ERR);
			res.setRetMsg("请求参数类型错误");
			log_.info("错误返回:"+res);
			return res;
		}

		ReqMessage req = (ReqMessage)o;
		String name = Thread.currentThread().getName();
		Thread.currentThread().setName(name + "_"+ req.getRpid());//将rpid放入线程名称中打印，便于日志的统计与分析
		
		res.setRpid(req.getRpid());

		//1、判断参数完整性
		if(StringUtil.isEmpty(req.getRpid())){
			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
			res.setRetCode(RetCode.REQPARAM_ERR);
			res.setRetMsg("rpid为空");
			log_.info("错误返回:"+res);
			return res;
		}else if(StringUtil.isEmpty(req.getReqDate())){
			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
			res.setRetCode(RetCode.REQPARAM_ERR);
			res.setRetMsg("reqDate为空");
			log_.info("错误返回:"+res);
			return res;
		}else if(StringUtil.isEmpty(req.getReqTime())){
			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
			res.setRetCode(RetCode.REQPARAM_ERR);
			res.setRetMsg("reqTime为空");
			log_.info("错误返回:"+res);
			return res;
		}
//		ThreadValue.put("rpid", req.getRpid());
		
		//2、去除请求参数中的空格
		Iterator<Map.Entry<String,Object>> it = req.getReqMap().entrySet().iterator();
		Map<String,Object>temp = new HashMap<String, Object>();
		while(it.hasNext()){
			Map.Entry<String,Object> entry = it.next();
			if(null != entry.getValue()){
				temp.put(entry.getKey(), entry.getValue());
			}
		}
		req.putAll(temp);
		
		//3、执行被拦截的方法
		try{
			res.setRpid(req.getRpid());
			res = (ResMessage)ctx.proceed();
			
			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
			//设置默认返回码及返回信息
			if(StringUtil.isEmpty(res.getRetCode()))
				res.setRetCode(RetCode.UNKNOWN);
			if(StringUtil.isEmpty(res.getRetMsg())){
				String retMsg = PropertiesUtil.getValue(res.getRetCode());
				if(StringUtil.isEmpty(retMsg)){
					retMsg = PropertiesUtil.getValue(RetCode.UNKNOWN);
				}
				res.setRetMsg(retMsg);
			}				
			
		}catch(Exception e){
			log_.error("执行方法"+ctx.getMethod()+"发生异常", e);
			if (e instanceof BusinessException) {
				BusinessException ce = (BusinessException) e;
				res.setRetCode(ce.getCode());
				res.setRetMsg(ce.getMessage());
				res.put(ce.getInfomation());
			}else{
				//系统忙请稍后再试
				String errCode = RetCode.UNKNOWN;
				String errMsg = PropertiesUtil.getValue(errCode);
				res.setRetCode(errCode);
				res.setRetMsg(errMsg);
			}
			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
			
		}finally{
			//如果返回报文中rpid为空，则填充rpid
			if(StringUtil.isEmpty(res.getRpid())) {
				res.setRpid(req.getRpid());
			}
		}
		return res;		
	}
}
